package com.xxl.job.executor.service.jobhandler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.godtree.model.BazhuanyuTask;
import com.godtree.service.IBazhuanyuTaskService;
import com.godtree.service.IRankCrawlerCollectionService;
import com.godtree.util.WranMsgUtils;
import com.godtree.util.bazhuayu.TaskTools;
import com.google.common.collect.Lists;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 获取八爪鱼正常的任务
 *
 * @author Lisicheng
 * @date 2022-10-16
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class BazhuayuTaskJob {

  private final IBazhuanyuTaskService bazhuanyuTaskService;
  private final IRankCrawlerCollectionService rankCrawlerCollectionService;

  @XxlJob("pullBazhuayuTask")
  public void createBazhuayuTask() {
    XxlJobHelper.log("开始拉取八爪鱼任务");
    bazhuanyuTaskService.createTask();
    XxlJobHelper.log("八爪鱼任务拉取完成");
  }

  @XxlJob("syncBazhuayuTaskData")
  public void syncTaskData() {
    XxlJobHelper.log("开始同步八爪鱼任务数据");
    bazhuanyuTaskService.syncData();
    XxlJobHelper.log("同步八爪鱼任务数据完成");
  }

  @XxlJob("syncBazhuanyuRankJob")
  public void bazhuanyuRankJob() {

    XxlJobHelper.log("开始将mongodb数据清洗成排名数据");

    List<BazhuanyuTask> taskList = bazhuanyuTaskService.list(
        Wrappers.<BazhuanyuTask>lambdaQuery().eq(BazhuanyuTask::getIsSync, true));

    if (CollUtil.isEmpty(taskList)) {
      XxlJobHelper.log("任务为空");
      return;
    }

    XxlJobHelper.log("任务数：{}", taskList.size());

    // 错误信息集合
    List<String> errMsgColl = Lists.newArrayList();
    // 定义一个标签，用于跳出多层循环
    one:
    for (Entry<String, List<BazhuanyuTask>> bazhuayuTask : taskList.stream()
        .collect(Collectors.groupingBy(BazhuanyuTask::getRankId)).entrySet()) {

      // 获取任务列表
      List<BazhuanyuTask> tasks = bazhuayuTask.getValue();
      // 如果任务列表为空，跳过
      if (CollUtil.isEmpty(tasks)) {
        continue;
      }

      // 遍历任务列表，检查任务状态，如果任务状态为运行中，跳过外层循环
      for (BazhuanyuTask task : tasks) {
        String taskId = task.getTaskId();
        // status定义为：运行中 = 0，已停止 = 1，已完成 = 2，待运行 = 3，未执行 = 5
        if (Objects.equals(TaskTools.getTaskStatus(Lists.newArrayList(taskId)).get(taskId), 0)) {
          XxlJobHelper.log("任务id：{}，任务名称：{}。正在运行中，跳过数据同步", taskId,
              task.getTaskName());
          continue one;
        }
      }

      try {
        // 如果任务列表中的任务状态都不是运行中，执行数据同步
        rankCrawlerCollectionService.rankDataByMongo(bazhuayuTask.getKey());
      } catch (Exception e) {
        String content = StrUtil.format("排名：{}。数据同步失败，原因：{}", bazhuayuTask.getKey(),
            ExceptionUtil.stacktraceToString(e));
        XxlJobHelper.log(content);
        errMsgColl.add(content);
      }

    }

    if (CollUtil.isNotEmpty(errMsgColl)) {
      String handleMsg = StrUtil.join(StrUtil.LF, errMsgColl);
      WranMsgUtils.send("排名数据清洗任务", handleMsg);
      XxlJobHelper.handleFail(handleMsg);
    }

    XxlJobHelper.log("将mongodb数据清洗成排名数据完成");

  }

}
